<template>
  <div class="dialog">
    <!-- 络筒弹窗控件 -->
    <a-modal
      :width="1400"
      :visible="Dialog"
      @cancel="closeDialog"
      :closable="true"
      :mask-closable="true"
      destroy-on-close
      :footer="null"
    >
      <div slot="title" class="clearfix">
        <div class="title" style="padding-left:20px"></div>
        <span class="title_top">{{ title }}</span>
      </div>
      <span class="title_time" style="margin-left:20px">{{ timenow }}</span>
      <a-row :gutter="12"> </a-row>
      <!-- mid -->
      <div class="lt-dialog-main">
        <div class="line-row">
          <div class="right">
            <div class="right-box" @click="clickSetBar('络纱时间', 'create_time')">
              <div class="title">
                络纱时间
              </div>
              <div class="inner">
                {{ queryInfo.create_time ? extractTimeOnly(queryInfo.create_time) : '00时00分00秒' }}
              </div>
            </div>
            <div class="right-box" @click="clickSetBar('产量', 'r23004')">
              <div class="title">
                产量（kg）
              </div>
              <div class="inner">{{ queryInfo.r23004 ? Number(queryInfo.r23004).toFixed(2) : 0 }}kg</div>
            </div>
            <div class="right-box" @click="clickSetBar('生产效率', 'r23005')">
              <div class="title">
                生产效率（%）
              </div>
              <div class="inner">{{ queryInfo.r23005 ? Number(queryInfo.r23005).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('班次', 'r21001')">
              <div class="title">
                班次
              </div>
              <div class="inner">{{ socketInfo.classes }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('品种', 'pz')">
              <div class="title">
                品种
              </div>
              <div class="inner">{{ socketInfo.productTypeTxt }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('员工', 'workers')">
              <div class="title">
                员工
              </div>
              <div class="inner">{{ queryInfo.workers }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('开始时间', 'r21004')">
              <div class="title">
                开始时间
              </div>
              <div class="inner">{{ queryInfo.r21004 ? formatDate(queryInfo.r21004) : '00-00-00' }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('实际开始时间', 'r21005')">
              <div class="title">
                实际开始时间
              </div>
              <div class="inner">{{ queryInfo.r21005 ? formatDate(queryInfo.r21005) : '00-00-00' }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('结束时间', 'r21006')">
              <div class="title">
                结束时间
              </div>
              <div class="inner">{{ queryInfo.r21006 ? formatDate(queryInfo.r21006) : '00-00-00' }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('机械效率', '')">
              <div class="title">
                机械效率（%）
              </div>
              <div class="inner">{{ (Number(socketInfo.efficiency) * 100).toFixed(2) }}%</div>
              <!-- <div class="inner">{{ Number(queryInfo.r23006).toFixed(2) }}%</div> -->
            </div>
            <div class="right-box" @click="clickSetBar('捻接循环次数', 'r23007')">
              <div class="title">
                捻接循环次数
              </div>
              <div class="inner">{{ queryInfo.r23007 ? Number(queryInfo.r23007).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('一次成功捻接次数', 'r23008')">
              <div class="title">
                一次成功捻接次数
              </div>
              <div class="inner">{{ queryInfo.r23008 ? Number(queryInfo.r23008).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('接头数', 'r23009')">
              <div class="title">
                接头数
              </div>
              <div class="inner">{{ queryInfo.r23009 ? Number(queryInfo.r23009).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('接头数/10km', 'r23010')">
              <div class="title">
                接头数/10km
              </div>
              <div class="inner">{{ queryInfo.r23010 ? Number(queryInfo.r23010).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('接头数/筒纱', 'r23011')">
              <div class="title">
                接头数/筒纱
              </div>
              <div class="inner">{{ queryInfo.r23011 ? Number(queryInfo.r23011).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('切疵次数', 'r23012')">
              <div class="title">
                切疵次数
              </div>
              <div class="inner">{{ queryInfo.r23012 ? Number(queryInfo.r23012).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('切疵/100km', 'r23013')">
              <div class="title">
                切疵/100km
              </div>
              <div class="inner">{{ queryInfo.r23013 ? Number(queryInfo.r23013).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('切疵/管纱', 'r23014')">
              <div class="title">
                切疵/管纱
              </div>
              <div class="inner">{{ queryInfo.r23014 ? Number(queryInfo.r23014).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('切疵/筒纱', 'r23015')">
              <div class="title">
                切疵/筒纱
              </div>
              <div class="inner">{{ queryInfo.r23015 ? Number(queryInfo.r23015).toFixed(2) : 15 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('满筒数', 'r23016')">
              <div class="title">
                满筒数
              </div>
              <div class="inner">{{ queryInfo.r23016 ? Number(queryInfo.r23016).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('小车落筒成功数', 'r23017')">
              <div class="title">
                小车落筒成功数
              </div>
              <div class="inner">{{ queryInfo.r23017 ? Number(queryInfo.r23017).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('换管数', 'r23018')">
              <div class="title">
                换管数
              </div>
              <div class="inner">{{ queryInfo.r23018 ? Number(queryInfo.r23018).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('络纱时间', 'r23019')">
              <div class="title">
                络纱时间
              </div>
              <div class="inner">{{ queryInfo.r23019 ? formatTime(queryInfo.r23019) : '00时00分00秒' }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('打结总数', 'r23020')">
              <div class="title">
                打结总数
              </div>
              <div class="inner">{{ queryInfo.r23020 ? Number(queryInfo.r23020).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('落筒总数', 'r23021')">
              <div class="title">
                落筒总数
              </div>
              <div class="inner">{{ queryInfo.r23021 ? Number(queryInfo.r23021).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('红灯总数', 'r23022')">
              <div class="title">
                红灯总数
              </div>
              <div class="inner">{{ queryInfo.r23022 ? Number(queryInfo.r23022).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('工艺总数', 'r23023')">
              <div class="title">
                工艺总数
              </div>
              <div class="inner">{{ queryInfo.r23023 ? Number(queryInfo.r23023).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('故障总数', 'r23024')">
              <div class="title">
                故障总数
              </div>
              <div class="inner">{{ queryInfo.r23024 ? Number(queryInfo.r23024).toFixed(2) : 0 }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('打结总时间', 'r23025')">
              <div class="title">
                打结总时间
              </div>
              <div class="inner">{{ queryInfo.r23025 ? formatTime(queryInfo.r23025) : '00时00分00秒' }}</div>
            </div>
            <div class="right-box" @click="clickSetBar('落筒总时间', 'r23026')">
              <div class="title">
                落筒总时间
              </div>
              <div class="inner">{{ queryInfo.r23026 ? formatTime(queryInfo.r23026) : '00时00分00秒' }}</div>
            </div>
          </div>
        </div>
        <div class="chart" ref="barChart"></div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { getMachineRealData } from '@/api/customApi'
export default {
  name: 'dialog_luotong',
  props: {
    defaultData: Object
  },
  data() {
    return {
      Dialog: false,
      title: '',
      title_l: '',
      data: '',
      timenow: '',
      isLoading: true,
      groupData: [],
      itemData: [],
      tableDataRow1: [],
      columns: [],
      queryInfo: {},
      socketInfo: {
        classes: '',
        productTypeTxt: ''
      },
      defaultBar:
        '[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]'
    }
  },
  created() {
    this.socketInfo = this.defaultData
    this.socketInfo.efficiency = this.defaultData.efficiency
    this.getInfo()
  },
  mounted() {},
  computed: {
    luoTongSocket() {
      let result
      if (this.$store.state.socketData.length != 0) {
        result = this.$store.state.socketData.find(item => item.workshop == this.$store.state.workshopNo)
        result = result.dsDeviceRealTimeStatusListSpooling
      }
      return result
    }
  },
  watch: {
    luoTongSocket: {
      immediate: true,
      handler(val) {
        if (val && this.queryInfo.deviceNo) {
          let result = val.filter(item => item.deviceNo == this.queryInfo.deviceNo)[0]
          this.socketInfo.status = result.status
          this.socketInfo.currentActualOutput = result.currentActualOutput
          this.socketInfo.currentTheoryOutput = result.currentTheoryOutput
          this.socketInfo.length = result.length
          this.socketInfo.efficiency = result.efficiency
        }
      }
    }
  },
  methods: {
    getInfo() {
      this.Dialog = true
      let query = {
        company: '1771136798305476610',
        deviceNo: this.defaultData.deviceNo,
        productCategory: this.defaultData.productCategory,
        workingProcedure: this.defaultData.workingProcedure,
        workshop: this.defaultData.workshop
      }
      getMachineRealData(query)
        .then(res => {
          if (res.code == 200) {
            this.queryInfo = res.result
            this.queryInfo.deviceNo = res.result.device_no
            this.queryInfo.realname = ''
            console.log('this.queryInfo', this.queryInfo)
          } else {
            this.$message.error('接口请求失败')
          }
        })
        .finally(() => {
          this.title_l = '络筒'
          this.title =
            '立华' +
            this.socketInfo.workshop +
            '纺' +
            this.socketInfo.productCode +
            '络筒' +
            this.socketInfo.deviceNo +
            '号详情'
          // this.title = `立华${this.$store.state.workshopNo}纺络筒${this.queryInfo.deviceNo}号机详情`
          this.timenow = moment().format('YYYY-MM-DD HH:mm')
          this.timer = setInterval(() => {
            this.timenow = moment().format('YYYY-MM-DD HH:mm')
          }, 60000)
          if (this.queryInfo.detail != null) {
            if (this.queryInfo.detail['r23004'] != '') {
              this.$nextTick(() => {
                this.setBar('络筒长度', this.queryInfo.detail['r23004'])
              })
            } else {
              this.$nextTick(() => {
                this.setBar('络筒长度', this.defaultBar)
              })
            }
          } else {
            this.$nextTick(() => {
              this.setBar('络筒长度', this.defaultBar)
            })
          }
        })
    },
    clickSetBar(name, ydata) {
      if (this.queryInfo.detail[ydata]) {
        this.setBar(name, this.queryInfo.detail[ydata])
      }
    },
    //时间戳转YYYY-MM-DD
    formatDate(timestamp) {
      const date = new Date(Number(timestamp))
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    extractTimeOnly(dateTimeString) {
      const date = new Date(dateTimeString)
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${hours}时${minutes}分${seconds}秒`
    },
    //时间戳转HH:mm:ss
    formatTime(timestamp) {
      let time = Number(timestamp)
      const date = new Date(time * 1000)
      const hours = date
        .getHours()
        .toString()
        .padStart(2, '0')
      const minutes = date
        .getMinutes()
        .toString()
        .padStart(2, '0')
      const seconds = date
        .getSeconds()
        .toString()
        .padStart(2, '0')
      return `${hours}时${minutes}分${seconds}秒`
    },
    setBar(name, ydata) {
      ydata = ydata.slice(1, -1).split(',')
      if (this.$refs.barChart) {
        let bar = this.$echarts.init(this.$refs.barChart)
        let length = ydata.length || 0
        let xdata = []
        for (let i = 0; i < length; i++) {
          xdata.push(i + 1)
        }
        let option = {
          grid: {
            left: 40,
            right: 40,
            bottom: 20
          },
          xAxis: {
            type: 'category',
            data: xdata,

            axisTick: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#000'
              }
            },
            axisLabel: {
              color: '#000',
              fontSize: 16
              // interval: 0 // 强制显示所有标签
            }
          },
          yAxis: {
            type: 'value',
            name: name,
            nameTextStyle: {
              color: '#000',
              fontSize: 16
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            axisLabel: {
              color: '#000',
              fontSize: 16
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(255,255,255,0.15)'
              }
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          series: [
            {
              data: ydata,
              type: 'bar',
              barWidth: 8,
              itemStyle: {
                normal: {
                  color: new this.$echarts.graphic.LinearGradient(
                    0,
                    0,
                    0,
                    1,
                    [
                      {
                        offset: 0,
                        color: '#1ACFD7' // 0% 处的颜色
                      },
                      {
                        offset: 0.98,
                        color: '#1AABFE' // 100% 处的颜色
                      }
                    ],
                    false
                  ),
                  borderRadius: 16
                }
              }
            }
          ]
        }

        bar.setOption(option)
        window.addEventListener('resize', function() {
          bar.resize()
        })
      }
    },
    secondsFormat(s) {
      var day = Math.floor(s / (24 * 3600)) // Math.floor()向下取整
      var hour = Math.floor((s - day * 24 * 3600) / 3600)
      var minute = Math.floor((s - day * 24 * 3600 - hour * 3600) / 60)
      var second = s - day * 24 * 3600 - hour * 3600 - minute * 60
      if (hour) {
        return hour + '时' + minute + '分' + second + '秒'
      } else {
        if (second < 10) {
          if (minute < 10) {
            return '0' + minute + '分' + second + '0秒'
          } else {
            return minute + '分' + second + '0秒'
          }
        } else {
          return minute + '分' + second + '0秒'
        }
      }
    },
    //明细工具类
    groupItemUtils(obj) {
      console.log('obj=====', obj)
      var itemList = []
      for (var i = 1; i <= 64; i++) {
        var list = {
          id: 'id' + i,
          no: '第' + i + '锭',
          lssj: obj.lssj ? this.secondsFormat(eval('(' + obj.lssj + ')')['lssj' + i]) : '',
          cx: eval('(' + obj.cx + ')')['cx' + i],
          pz: obj.pz,
          dqbc: obj.dqbc,
          mj: eval('(' + obj.mj + ')')['mj' + i],
          dc: eval('(' + obj.dc + ')')['dc' + i],
          nj: eval('(' + obj.nj + ')')['nj' + i],
          xh: eval('(' + obj.xh + ')')['xh' + i],
          qc: eval('(' + obj.qc + ')')['qc' + i],
          yj: eval('(' + obj.yj + ')')['yj' + i],
          hg: eval('(' + obj.hg + ')')['hg' + i],
          cz: eval('(' + obj.cz + ')')['cz' + i],
          xtq: eval('(' + obj.xq + ')')['xq' + i],
          yx: eval('(' + obj.yx + ')')['yx' + i],
          mt: eval('(' + obj.mt + ')')['mt' + i],
          cc: eval('(' + obj.cc + ')')['cc' + i],
          bc: eval('(' + obj.bc + ')')['bc' + i],
          xl: (Number(eval('(' + obj.xl + ')')['xl' + i]) * 100).toFixed(0) + '%'
        }
        itemList.push(list)
      }
      this.isLoading = false
      return itemList
    },
    //分组工具类
    groupUtils(obj) {
      var tableDataRow1 = []

      for (var i = 1; i <= 4; i++) {
        var no = ''
        if (i == 1) {
          no = '第一分组 (1锭 ~ 16锭)品种:络筒'
        } else if (i == 2) {
          no = '第二分组 (17锭 ~ 32锭)品种:络筒'
        } else if (i == 3) {
          no = '第三分组 (33锭 ~ 48锭)品种:络筒'
        } else if (i == 4) {
          no = '第四分组 (49锭 ~ 64锭)品种:络筒'
        }
        var key = 'sum' + i
        var list = {
          id: i,
          lssj: '',
          no: no,
          pz: obj.pz,
          dqbc: obj.dqbc,
          cx: obj.cx[key],
          mj: obj.mj[key],
          dc: '',
          nj: obj.nj[key],
          xh: obj.xh[key],
          qc: obj.qc[key],
          yj: obj.yj[key],
          hg: obj.hg[key],
          cz: obj.cz[key],
          xtq: obj.xtq[key],
          yx: obj.yx[key],
          mt: obj.mt[key],
          cc: obj.cc[key],
          bc: obj.bc[key],
          xl: (Number(obj.xl) * 100).toFixed(2) + '%',
          hasChildren: true
        }
        console.log(list)
        tableDataRow1.push(list)
      }

      return tableDataRow1
    },
    // 获取连续Ds
    getSeiresDs(arr) {
      var result = [],
        i = 0,
        str = ''
      if (arr.length > 0) {
        result[i] = [arr[0]]
        arr.reduce(function(prev, cur) {
          parseInt(cur) - parseInt(prev) == 1 ? result[i].push(cur) : (result[++i] = [cur])
          return cur
        })
        result.map(item => {
          if (item.length > 1) {
            str += `${item[0]} - ${item[item.length - 1]}锭、`
          } else {
            str += `#${item[0]}锭、`
          }
        })
        str = str.substring(0, str.length - 1)
      } else {
        str = ''
      }
      return str
    },
    //尾灯表示车台状态（运行、停止、故障、满纱满桶、通讯失败/停电)
    getHeadColor(status) {
      switch (parseInt(status)) {
        //运行
        case 1:
          return '#02DE6D'
        //停止
        case 2:
          return '#FF3C00'
        //故障
        case 3:
          return '#FF9902'
        //满纱满桶
        case 4:
          return '#00D8D3'
        //通讯失败/停电
        case 5:
          return '#B8B8B8'
        // 计划停台
        case 6:
          return 'rgb(255,233,34)'
        default:
          return '#B8B8B8'
      }
    },
    getHeadName(stateCode) {
      switch (parseInt(stateCode)) {
        //运行
        case 1:
          return '运行'
        //停止
        case 2:
          return '停止'
        //故障
        case 3:
          return '故障'
        //满纱满桶
        case 4:
          return '满纱满桶'
        //通讯失败/停电
        case 5:
          return '通讯失败/停电'
        // 计划停台
        case 6:
          return '计划停台'
        default:
          return '通讯失败/停电'
      }
    },
    showDialog(data) {},
    closeDialog() {
      this.isLoading = true
      this.itemData.splice(0, this.itemData.length)
      this.tableDataRow1.splice(0, this.tableDataRow1.length)
      this.$parent.closeHandle()
      this.timer = null
    },
    init() {
      if (this.$refs.lulotongEcharts) {
        var lulotongEcharts = this.$echarts.init(this.$refs.lulotongEcharts)
        var option = {
          series: [
            {
              type: 'gauge',

              center: ['50%', '50%'],
              radius: '90%',
              min: 0,
              max: 100,
              itemStyle: {
                color: '#58D9F9',
                shadowColor: 'rgba(0,138,255,0.45)',
                shadowBlur: 10,
                shadowOffsetX: 2,
                shadowOffsetY: 2
              },
              axisLine: {
                roundCap: true,
                lineStyle: {
                  width: 15,
                  color: [[1, '#1D3E52']]
                }
              },

              progress: {
                roundCap: true,
                show: true,
                width: 18
              },

              axisTick: {
                show: true
              },
              splitLine: {
                show: false,
                length: 15
              },

              axisLabel: {
                distance: 5,
                color: '#62C6F3',
                fontSize: 9
              },
              anchor: {
                show: false
              },

              title: {
                offsetCenter: [0, '85%'],
                fontSize: 20,
                color: '#58D9F9'
              },
              detail: {
                valueAnimation: true,
                fontSize: 28,
                fontFamily: 'electronicFont',
                offsetCenter: [0, '60%'],
                color: 'rgb(241,241,64)',
                formatter: function(value) {
                  return Math.round(value) + '%'
                }
              },

              data: [
                {
                  name: '效率',
                  value: (Number(this.socketInfo.efficiency) * 100).toFixed(2)
                    ? (Number(this.socketInfo.efficiency) * 100).toFixed(2)
                    : 0
                }
              ]
            }
          ]
        }

        lulotongEcharts.setOption(option)
        window.addEventListener('resize', function() {
          lulotongEcharts.resize()
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/assets/less/workshop.less';
.ant-row {
  margin-bottom: 15px;
  &:last-child {
    margin-bottom: 0;
  }
}
.echarts {
  width: 100%;
  height: 200px;
}
.title {
  color: black;
}
.lt-dialog {
  ::v-deep.ant-modal-body {
    height: 740px;
    overflow-y: auto;
  }
  .row1 {
    height: 40px;
    margin-bottom: 0;
    line-height: 40px;
    box-sizing: border-box;
    padding-top: 0;
    padding-bottom: 0;
    border-radius: 2px;
  }
  &-main {
    box-sizing: border-box;
    padding: 23px;
    .line-row {
      display: flex;
      .left {
        width: 146px;
        flex-shrink: 0;
        margin-right: 12px;
        &-txt {
          margin-top: 10px;
          color: black;
          font-size: 18px;
          line-height: 25px;
        }
      }
      .right {
        display: grid;
        width: 100%;
        grid-template-columns: repeat(auto-fill, 200px);
        grid-template-rows: repeat(auto-fill, 62px);
        grid-column-gap: 10px;
        grid-row-gap: 10px;
        &-box {
          width: 200px;
          height: 62px;
          border-radius: 2px;
          border: 1px solid #00e9fc;
          box-sizing: border-box;
          cursor: pointer;
          .title {
            width: 100%;
            height: 26px;
            border-bottom: 1px solid #00e9fc;
            color: black;
            text-align: center;
            font-size: 16px;
          }
          .inner {
            height: 36px;
            line-height: 33px;
            text-align: center;
            color: black;
            font-size: 18px;
          }
        }
      }
    }
    .chart {
      width: 100%;
      height: 200px;
    }
  }
  .footer {
    .page {
      line-height: 38px;
      margin: 0 32px;
      color: black;
      font-size: 24px;
    }
    .a-button {
      width: 124px;
      height: 40px;
      font-size: 18px;
      padding: 0;
      color: black;
      line-height: 38px;
      text-align: center;
      border-radius: 2px;
      border: 1px solid #00e2f5;
    }
  }
}
</style>
